package com.dftc.dftcdemo.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class OssUpLoadUtile {
    protected String mBucketName;
    protected String mPublicBucketName;
    private OSSClient mOSS;
    String TAG = OssUpLoadUtile.class.getSimpleName();


    public OSS initOSSClient(Context context) {
        if (mOSS == null) {
            OSSCredentialProvider provider = OSSConfig.newCustomSignerCredentialProvider();
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            mOSS = new OSSClient(context, OSSConfig.ENDPOINT, provider, conf);
        }
        return mOSS;
    }

    public void upload(File file) {
        upload(0, file, new OnUploadListener() {
            @Override
            public void onProgress(int position, long currentSize, long totalSize) {

            }

            @Override
            public void onSuccess(int position, String uploadLocalPath, String imageUrl) {
                Log.e(TAG, "上传成功 " + imageUrl);
            }

            @Override
            public void onFailure(String fileName) {
                Log.e(TAG, "上传失败 " + fileName);
            }
        });
    }


    /**
     * 图片上传
     *
     * @param file             图片的本地路径
     * @param onUploadListener 回调监听
     */
    public void upload(final int position, final File file,
                       final OnUploadListener onUploadListener) {
        Observable.just(mOSS)
                .map(new Function<OSS, String>() {
                    @Override
                    public String apply(OSS oss) throws Exception {
                        // 创建上传的对象
                        PutObjectRequest put = new PutObjectRequest(OSSConfig.buketName,
                                OSSConfig.mac + file.getName()
                                , file.getAbsolutePath());
                        // 上传的进度回调
                        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                                if (onUploadListener == null) {
                                    return;
                                }
                                onUploadListener.onProgress(position, currentSize, totalSize);
                            }
                        });
                        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                if (onUploadListener == null) {
                                    return;
                                }
                                String imageUrl = request.getObjectKey();
                                onUploadListener.onSuccess(position, file.getAbsolutePath(),
                                        "" + imageUrl);
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                serviceException.printStackTrace();
                                clientException.printStackTrace();
                                if (onUploadListener == null) {
                                    return;
                                }
                                onUploadListener.onFailure(file.getAbsolutePath());
                            }
                        });
                        return OSSConfig.buketName + file.getName();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
    }


    /**
     * 图片上传
     *
     * @param bytes            jpg图片字节
     * @param onUploadListener 回调监听
     */
    public void upload(final String fileName, final byte[] bytes,
                       final OnUploadListener onUploadListener) {
        Observable.just(mOSS)
                .map(new Function<OSS, String>() {
                    @Override
                    public String apply(OSS oss) throws Exception {
                        // 创建上传的对象
                        PutObjectRequest put = new PutObjectRequest(OSSConfig.buketName,
                                uploadPath() + OSSConfig.mac + fileName
                                , bytes);
                        // 上传的进度回调
                        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                                if (onUploadListener == null) {
                                    return;
                                }
                                onUploadListener.onProgress(0, currentSize, totalSize);
                            }
                        });
                        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                if (onUploadListener == null) {
                                    return;
                                }
                                String imageUrl = request.getObjectKey();
                                onUploadListener.onSuccess(0, fileName,
                                        "" + imageUrl);
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                serviceException.printStackTrace();
                                clientException.printStackTrace();
                                if (onUploadListener == null) {
                                    return;
                                }
                                onUploadListener.onFailure(fileName);
                            }
                        });
                        return OSSConfig.buketName + fileName;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
    }


    public interface OnUploadListener {
        /**
         * 上传的进度
         */
        void onProgress(int position, long currentSize, long totalSize);

        /**
         * 成功上传
         */
        void onSuccess(int position, String uploadLocalPath, String imageUrl);

        /**
         * 上传失败
         */
        void onFailure(String fileName);
    }


    private String uploadPath() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        Log.d("now time is", sdf.format(d));
        return sdf.format(d);
    }


    /**
     * 保存图片到本地
     */
    private void savePic(byte[] headerBytes, String path, long usedTime, long startTime) {
        Bitmap bitmap;
        byte[] jdata = headerBytes;

        Log.d(TAG, "图像字节长度 " + headerBytes.length);
        bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);

        if (null != bitmap) {
            Bitmap newBitmap;
            newBitmap = bitmap;
            String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DFTCface/";
            File file1 = new File(dir);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            File file = new File(dir + path);
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
                startTime = System.currentTimeMillis() - startTime;
                usedTime = usedTime + startTime;
                String name = dir + path.replace(".jpg", "T" + usedTime + ".jpg");
                File localFile = new File(name);
                boolean result = file.renameTo(localFile);
                Log.d(TAG, "save result is " + result);
                upload(localFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.d(TAG, "读取 图像文件 为空");
        }
    }
}
